<template>
  <ConfigProvider
    :theme="{
      token: {
        colorBgElevated: '#4F5F79',
      },
    }"
  >
    <contextHolder />
  </ConfigProvider>
</template>

<script setup lang="tsx">
import { computed, h, inject, ref, useTemplateRef, watch } from 'vue';
import { useUserStore } from '@/stores/modules';
import { ExclamationCircleFilled } from '@ant-design/icons-vue';
import { Button, ConfigProvider, Space, notification } from 'ant-design-vue';
import { useWebSocket } from '@/hooks/useNotice';
import { useSpeechSynthesis } from '@/hooks/useSpeechSynthesis';
import { audioRefKey } from '@/constant/injectKey';

const audioRef = inject(audioRefKey);

enum Level {
  '警告' = 1,
  '普通',
  '提示',
}

enum LevelColor {
  '#4189F5' = 1,
  '#F5B941',
  '#F5415F',
}

enum StatusEnum {
  '待处理',
  '已处理',
  '已完结',
  '已撤销',
}

const { createUtterance, speak, stop } = useSpeechSynthesis();

const key = 'NOTICE_MESSAGE_KEY';
const current = ref(0);

const prev = () => {
  if (current.value > 0) {
    current.value--;
    openNotification();
  }
};
const next = () => {
  if (current.value < localMessage.value.length) {
    current.value++;
    openNotification();
  }
};
const [api, contextHolder] = notification.useNotification({});

// 1 提示 2 普通 3警告
const openNotification = () => {
  const messageStr = localMessage.value[current.value];
  if (messageStr) {
    const data = JSON.parse(messageStr);
    const color = LevelColor[data.alarmLevel];
    const icon = () => {
      return h(ExclamationCircleFilled, {
        style: {
          color,
          fontSize: '36px',
        },
      });
    };
    const message = () => (
      <div
        style={{
          color,
          paddingLeft: '12px',
          fontWeight: 700,
          fontSize: '16px',
        }}
      >
        {`${data.monitorItem}-${data.status !== undefined ? StatusEnum[data.status] : Level[data.alarmLevel || 3]}`}
      </div>
    );

    const content = () => {
      return (
        <div class=' text-sm leading-[22px]'>
          {data.description.split('\n').map((item: string) => {
            return <div>{item}</div>;
          })}
        </div>
      );
    };

    api.warning({
      class: 'custom-notice',
      icon,
      message,
      description: content,
      placement: 'bottomRight',
      key,
      duration: null,
      btn() {
        return localMessage.value.length > 1 ? (
          <Space>
            <span>
              {current.value + 1} / {localMessage.value.length}
            </span>
            <Button
              type='link'
              disabled={current.value === 0}
              onClick={() => prev()}
            >
              上一条
            </Button>
            <Button
              type='link'
              disabled={current.value + 1 === localMessage.value.length}
              onClick={() => next()}
            >
              下一条
            </Button>
          </Space>
        ) : (
          <></>
        );
      },
      onClose: cleanMessage,
    });
  }
};

const userStore = useUserStore();
// console.log(location.protocol);

// const protocol = location.protocol === 'http:' ? 'ws' : 'wss';
// const url = `${protocol}://${location.host}/api/websocket/${userStore.userId}`;
const url = `ws://${VITE_WS_HOST}:9622/api/websocket/${userStore.userId}`;

const { message, cleanMessage } = useWebSocket(url);
const localMessage = computed(() => {
  return message.value.filter((item) => {
    return item !== 'pong';
  });
});

const handleMessage = async () => {
  if (localMessage.value.length) {
    openNotification();
    const { content, isHaveSound } = JSON.parse(localMessage.value.at(-1)!);
    if (isHaveSound !== '1') return;
    audioRef?.value?.play();
    // stop();
    // createUtterance(content);
    // speak();
  }
};

watch(() => localMessage.value, handleMessage);
</script>

<style lang="scss">
.custom-notice {
  width: 402px;
  height: 212px;
  background: url(@/assets/images/notice/bg.png) no-repeat;
  background-size: 442px 252px;
  background-position: -19px -20px;
  padding: 18px;
}
</style>
